package com.jack.leetcode.每日一题;

import java.util.Arrays;

/***
 * @author zhangjie
 * @date 2020/3/31 21:43
 */
public class 排序数组 {
    public static void main(String[] args) {
        int[] a = {9, 8, 7, 5, 6, 1, 2, 3, 4};
        int[] array = sortArray(a);
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }

    public static int[] sortArray(int[] nums) {
        int[] tmp = Arrays.copyOf(nums, nums.length);
        sort(nums, 0, nums.length - 1, tmp);
        return tmp;
    }

    public static void sort(int[] a, int left, int right, int[] tmp) {
        if (left < right) {
            int mid = (left + right) / 2;
            sort(a, left, mid, tmp);
            sort(a, mid + 1, right, tmp);
            merge(a, left, mid, right, tmp);
        }
    }

    public static void merge(int[] a, int left, int mid, int right, int[] tmp) {
        int i = left;
        int j = mid + 1;
        int t = 0;
        while (i <= mid && j <= right) {
            if (a[i] > a[j]) {
                tmp[t++] = a[j++];
            } else {
                tmp[t++] = a[i++];
            }
        }
        while (i <= mid) {
            tmp[t++] = a[i++];
        }
        while (j <= right) {
            tmp[t++] = a[j++];
        }
        t = 0;
        while (left <= right) {
            a[left++] = tmp[t++];
        }
    }
}
